package com.neusoft.zqygbc.neusoft_wenda.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.jaiky.imagespickers.ImageConfig;
import com.jaiky.imagespickers.ImageSelector;
import com.jaiky.imagespickers.ImageSelectorActivity;
import com.neusoft.zqygbc.neusoft_wenda.R;
import com.neusoft.zqygbc.neusoft_wenda.base.RetrofitCallback;
import com.neusoft.zqygbc.neusoft_wenda.javeBean.Question;
import com.neusoft.zqygbc.neusoft_wenda.javeBean.Status;
import com.neusoft.zqygbc.neusoft_wenda.model.QusetionModel;
import com.neusoft.zqygbc.neusoft_wenda.service.QuestionService;
import com.neusoft.zqygbc.neusoft_wenda.utils.AudioRecoderUtils;
import com.neusoft.zqygbc.neusoft_wenda.utils.GlideLoader;
import com.neusoft.zqygbc.neusoft_wenda.utils.MapUtils;
import com.neusoft.zqygbc.neusoft_wenda.utils.PopupWindowFactory;
import com.neusoft.zqygbc.neusoft_wenda.utils.TimeUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NewQuestionActivity extends CheckPermissionsActivity {
    private Intent intent;
    private SharedPreferences sp;
    private EditText new_question_description;
    private EditText new_qusestion_textcontent;
    private TextView tv1;
    private Spinner spinner;
    private List<String> data_list;
    private List<String> pathList;
    private String a;
    private Map<String, RequestBody> bodyMap;
    private ArrayAdapter<String> arr_adapter;
    private String tid = "1";
    private String tname = "Android";
    private ArrayList<String> path = new ArrayList<>();
    public static final int REQUEST_CODE = 123;
    private ImageConfig imageConfig;
    private LinearLayout llContainer;
    private ImageView btn_new_question_photo;
    private ImageView new_question_return;
    private ImageView btn_new_question_send;
    private QusetionModel questionModel;
    private Call call;
    private RetrofitCallback<Question> questionDetailCallback;
    private String[] filename;
    private ImageView btn_new_question_location;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private TextView new_question_location;
    private Button btn_new_question_voice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_question);
        initViews();
        initEvents();
        //初始化定位
        initLocation();


    }



    private void initEvents() {
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                tname = (String) spinner.getSelectedItem();
                if (tname.equals("Android")) {
                    tid = "1";

                } else if (tname.equals("PHP")) {
                    tid = "2";

                } else if (tname.equals("Web")) {
                    tid = "3";

                } else if (tname.equals("iOS")) {
                    tid = "4";

                }
                //把该值传给 TextView
                // tv.setText(str);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        btn_new_question_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageConfig = new ImageConfig.Builder(
                        new GlideLoader())
                        .steepToolBarColor(getResources().getColor(R.color.titleBlue))
                        .titleBgColor(getResources().getColor(R.color.titleBlue))
                        .titleSubmitTextColor(getResources().getColor(R.color.white))
                        .titleTextColor(getResources().getColor(R.color.white))
                        // 开启多选   （默认为多选）
                        .mutiSelect()
                        // 多选时的最大数量   （默认 8 张）
                        .mutiSelectMaxSize(8)
                        //设置图片显示容器，参数：、（容器，每行显示数量，是否可删除）
                        .setContainer(llContainer, 4, true)
                        // 已选择的图片路径
                        .pathList(path)
                        // 拍照后存放的图片路径（默认 /temp/picture）
                        .filePath("/temp")
                        // 开启拍照功能 （默认关闭）
                        .showCamera()
                        .requestCode(REQUEST_CODE)
                        .build();
                ImageSelector.open(NewQuestionActivity.this, imageConfig);

            }
        });
        new_question_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_new_question_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });

        btn_new_question_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocation();

            }
        });


    }


    private void initData() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://115.159.93.244/wenda/api.php/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        QuestionService questionService = retrofit.create(QuestionService.class);
        Call<Status> call = questionService.addquestion(sp.getString("user_id", ""),
                new_question_description.getText().toString(),
                tid,
                new_qusestion_textcontent.getText().toString(),
                bodyMap);
        call.enqueue(new Callback<Status>() {
            @Override
            public void onResponse(Call<Status> call, Response<Status> response) {
                if (response.body().getCode().toString().equals("1")) {
                    Toast.makeText(NewQuestionActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(NewQuestionActivity.this, MainActivity.class);
                    startActivity(intent);

                } else {
                    Toast.makeText(NewQuestionActivity.this, "发布失败" + response.body().getCode(), Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onFailure(Call<Status> call, Throwable t) {

            }
        });
    }


    private void initViews() {
        intent = getIntent();
        sp = getSharedPreferences("userinfo", MODE_PRIVATE);

        new_question_location = (TextView) findViewById(R.id.new_question_location);
        new_question_description = (EditText) findViewById(R.id.new_question_description);
        new_qusestion_textcontent = (EditText) findViewById(R.id.new_qusestion_textcontent);
        new_question_return = (ImageView) findViewById(R.id.new_question_return);
        btn_new_question_photo = (ImageView) findViewById(R.id.btn_new_question_photo);
        btn_new_question_location = (ImageView) findViewById(R.id.btn_new_question_location);
        llContainer = (LinearLayout) findViewById(R.id.new_question_photo);
        btn_new_question_send = (ImageView) findViewById(R.id.btn_new_question_send);
        spinner = (Spinner) findViewById(R.id.sp);
        data_list = new ArrayList<String>();
        data_list.add("Android");
        data_list.add("PHP");
        data_list.add("Web");
        data_list.add("iOS");
        //适配器
        arr_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner.setAdapter(arr_adapter);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);

            // tv1.setText("");
            for (String path : pathList) {

                // tv1.append(path);
                // tv1.append("\n");
            }

            path.clear();
            path.addAll(pathList);
            // String[] filename=new String[pathList.size()];
            bodyMap = new HashMap<>();
            ArrayList fname = new ArrayList();
            for (int i = 0; i < pathList.size(); i++) {
                File file = new File(pathList.get(i));
                bodyMap.put("file" + i + "\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
                fname.add(pathList.get(i).substring(pathList.get(i).lastIndexOf("/") + 1));
                //System.out.println("赵庆阳"+fname.get(i));
                //  filename[i]=(String)fname.get(i);
                //System.out.println("魏莹悦"+filename[i]);
                //System.out.println("赵庆阳"+ pathList.get(i).substring(pathList.get(i).lastIndexOf("/")+1));
            }
            filename = (String[]) fname.toArray(new String[pathList.size()]);
            for (int i = 0; i < filename.length; i++) {
                System.out.println("aa" + filename[i]);
            }
        }

    }


    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        if (null == locationOption) {
            locationOption = new AMapLocationClientOption();
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        }
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }


    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
                    //sb.append("定位成功" + "\n");
/*                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");*/
                   // sb.append("地    址    : " + location.getAddress() + "\n");
                    //sb.append("兴趣点    : " + location.getPoiName() + "\n");
                    sb.append( location.getPoiName() + "\n");
                    //定位完成的时间
                   // sb.append("定位时间: " + MapUtils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                }
                //定位之后的回调时间
               // sb.append("回调时间: " + MapUtils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
                new_question_location.setText(result);
            } else {
                new_question_location.setText("定位失败，loc is null");
            }
        }
    };

    /**
     * 开始定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {
        //根据控件的选择，重新设置定位参数
        resetOption();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    // 根据控件的选择，重新设置定位参数
    private void resetOption() {
        // 设置是否需要显示地址信息
        locationOption.setNeedAddress(true);
        /**
         * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
         * 注意：只有在高精度模式下的单次定位有效，其他方式无效
         */
        locationOption.setGpsFirst(true);
        // 设置是否开启缓存
        locationOption.setLocationCacheEnable(true);
        // 设置是否单次定位
        locationOption.setOnceLocation(true);
        //设置是否等待设备wifi刷新，如果设置为true,会自动变为单次定位，持续定位时不要使用
        locationOption.setOnceLocationLatest(true);
        //设置是否使用传感器
        locationOption.setSensorEnable(true);
        //设置是否开启wifi扫描，如果设置为false时同时会停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        String strInterval = "";
        if (!TextUtils.isEmpty(strInterval)) {
            try {
                // 设置发送定位请求的时间间隔,最小值为1000，如果小于1000，按照1000算
                locationOption.setInterval(Long.valueOf(strInterval));
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }

        String strTimeout = "";
        if (!TextUtils.isEmpty(strTimeout)) {
            try {
                // 设置网络请求超时时间
                locationOption.setHttpTimeOut(Long.valueOf(strTimeout));
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

}
